import { FeatureCollection, Feature, Polygon } from "geojson";

interface OriginalCountyData {
  name: string;
  pcode: string;
  bh: string;
  lx: number;
  shape: string;
}

export function transformToGeoJSON(data: OriginalCountyData[]): FeatureCollection {
  const features: Feature<Polygon>[] = data
    .map((county) => {
      // 解析 POLYGON 坐标字符串
      const coordinatesMatch = county.shape.match(/POLYGON\(\((.*)\)\)/);
      if (!coordinatesMatch) {
        console.warn(`Invalid shape for county: ${county.name}`);
        return null;
      }

      const coordinateStrings = coordinatesMatch[1].split(",");
      const coordinates = coordinateStrings.map((coord) => {
        const [lon, lat] = coord.trim().split(" ").map(parseFloat);
        return [lon, lat];
      });

      // 确保多边形闭合
      if (
        coordinates[0][0] !== coordinates[coordinates.length - 1][0] ||
        coordinates[0][1] !== coordinates[coordinates.length - 1][1]
      ) {
        coordinates.push(coordinates[0]);
      }

      return {
        type: "Feature",
        geometry: {
          type: "Polygon",
          coordinates: [coordinates],
        },
        properties: {
          name: county.name,
          pcode: county.pcode,
          bh: county.bh,
          lx: county.lx,
        },
      };
    })
    .filter(Boolean) as Feature<Polygon>[];

  data.forEach((county) => {
    const point = county.shape.match(/POINT\((.*)\)/);
    if (point) {
      features.forEach((item) => {
        if (item.properties?.name === county.name) {
          item.properties.cp = point[1].split(" ").map(parseFloat);
        }
      });
    }
  });
  return {
    type: "FeatureCollection",
    features: features,
  };
}

// 为 ECharts 特殊处理的转换函数
export function convertForECharts(data: any): any {
  const geoJsonData = transformToGeoJSON(data.data);

  // 转换为 ECharts 期望的格式
  return {
    type: "FeatureCollection",
    features: geoJsonData.features.map((feature) => ({
      type: "Feature",
      geometry: feature.geometry,
      properties: {
        ...feature.properties,
        name: feature.properties.name,
        cp: feature.properties.cp || [0, 0],
      },
    })),
  };
}

// 使用示例
export function convertTestJson(test: any) {
  const geoJsonData = convertForECharts(test);
  // console.log('GeoJSON 转换完成', geoJsonData);
  return geoJsonData;
}
